package com.zyf.system.service;

import com.zyf.system.controller.vo.DepartmentTreeVo;
import com.zyf.system.db.mysql.Department;
import com.zyf.system.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张云帆
 * 2025/3/26 14:55
 */
@Service
public class DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 获取科室树形结构
     */
    public List<DepartmentTreeVo> getDepartmentTree() {
        // 1. 查询所有科室数据
        List<Department> departments = departmentRepository.findAll();

        // 2. 转换为 DTO 列表
        List<DepartmentTreeVo> dtos = departments.stream()
                .map(d -> new DepartmentTreeVo(d.getId(), d.getName(), d.getParentId(), d.getDescription(),
                        d.getIsDeleted(), null))
                .collect(Collectors.toList());

        // 3. 构建树形结构
        Map<Integer, DepartmentTreeVo> nodeMap = new HashMap<>();
        List<DepartmentTreeVo> rootNodes = new ArrayList<>();

        // 3.1 将所有节点存入 Map（id → DTO）
        for (DepartmentTreeVo dto : dtos) {
            nodeMap.put(dto.getId(), dto);
        }

        // 3.2 构建父子关系
        for (DepartmentTreeVo dto : dtos) {
            Integer parentId = dto.getParentId();
            if (parentId == null || parentId == 0) {
                // 根节点（无父节点）
                rootNodes.add(dto);
            } else {
                // 找到父节点，将当前节点加入其 children
                DepartmentTreeVo parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(dto);
                }
            }
        }

        return rootNodes;
    }
}
